/*
 *                    _ooOoo_
 *                   o8888888o
 *                   88" . "88
 *                   (| -_- |)
 *                   O\  =  /O
 *                ____/`- -'\____
 *              .'  \\|     |//  `.
 *             /  \\|||  :  |||//  \
 *            /  _||||| -:- |||||-  \
 *            |   | \\\  -  /// |   |
 *            | \_|  ''\- -/''  |   |
 *            \  .-\__  `-`  ___/-. /
 *          ___`. .'  /- . -\  `. . __
 *       ."" '<  `.___\_<|>_/___.'  >'"".
 *      | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *      \  \ `-.   \_ __\ /__ _/   .-` /  /
 * ======`-.____`-.___\_____/___.-`____.-'======
 *                    `=- -='
 * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 *           佛祖保佑       永无BUG
 * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 */

package com.softeem.starwars.entity;

import com.softeem.starwars.panel.GamePanel;
import com.softeem.starwars.sound.SoundPool;
import com.softeem.starwars.utils.ImageLoader;
import com.softeem.starwars.utils.Settings;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 玩家类
 * @Author mrchai 2020/4/8 16:43
 */
public class Player extends Sprite{

    private Timer timer;
    private int flag;
    private int speed = 5;

    @Override
    public void init() {
        timer = new Timer();
        BufferedImage img = ImageLoader.load("player/player_0.png");
        setImg(img);
        setWidth(img.getWidth());
        setHeight(img.getHeight());
        setY((Settings.HEIGHT - getHeight())/2);
        timer.schedule(new PlayerFly(),0,100);
    }

    public void shoot() {
        new SoundPool(SoundPool.SHOOT,false).start();
        Bullet b = new Bullet(getX() + getWidth(),getY());
        GamePanel.bullets.add(b);
        new Thread(b).start();
    }

    /**
     * 玩家飞行动画
     */
    class PlayerFly extends TimerTask{
        @Override
        public void run() {
            setImg(ImageLoader.load("player/player_"+(flag++ % 4)+".png"));
        }
    }


    /**
     * 移动
     */
    public void move(int keyCode){
        System.out.println(keyCode+"==========");
        switch(keyCode){
            case 37:
                //左
                setX(getX() - speed);
                break;
            case 38:
                //上
                setY(getY() - speed);
                break;
            case 39:
                //右
                setX(getX() + speed);
                break;
            case 40:
                //下
                setY(getY() + speed);
                break;
        }
    }

    @Override
    public void draw(Graphics g) {
        g.drawImage(getImg(),getX(),getY(),getWidth(),getHeight(),null);
    }

    @Override
    public void destroy() {
        System.out.println("玩家死亡");
        if(timer != null){
            timer.cancel();
        }
    }
}
